<template>
  <div>
    <the-table
      :data="course"
      :pageInfo="queryInfo"
      :total="total"
      @pageInfoChange="pageInfoChange"
      @handleAdd="goToAdd"
      :layout="['addBtn', 'search', 'column']"
      :columns="columns"
      @changeColumn="changeColumn"
      @search="search"
      @clearInput="getClass"
    >
      <!-- 表格区 -->

      <!-- 拓展区 -->
      <el-table-column type="expand">
        <template #default="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="课程介绍：">
              <span v-if="props.row.introduction">{{
                props.row.introduction
              }}</span>
              <span v-else>暂无课程介绍</span>
            </el-form-item>
            <el-form-item label="封面图片：">
              <el-image
                v-if="props.row.cover"
                style="width: 100px; height: 100px"
                :src="props.row.cover"
                :fit="fit"
              ></el-image>
              <span v-else>暂无封面图片</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <!-- 表格区 -->
      <el-table-column
        label="课程名称"
        prop="name"
        v-if="columns[0].show"
      ></el-table-column>
      <el-table-column
        label="课程类型"
        prop="typeInfo.type"
        v-if="columns[1].show"
      ></el-table-column>
      <el-table-column
        label="教师"
        prop="teacher"
        v-if="columns[2].show"
      ></el-table-column>
      <el-table-column
        label="所属机构"
        prop="organization"
        v-if="columns[3].show"
      ></el-table-column>
      <el-table-column
        label="视频数量"
        prop="video_num"
        v-if="columns[4].show"
      ></el-table-column>
      <el-table-column
        label="作业数量"
        prop="homework_num"
        v-if="columns[5].show"
      ></el-table-column>
      <el-table-column label="评分" prop="score" v-if="columns[6].show">
        <template #default="scope">
          <el-rate v-model="scope.row.score" disabled></el-rate>
        </template>
      </el-table-column>
      <!-- 操作区域 -->
      <el-table-column label="操作" width="200px" v-if="columns[7].show">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            style="color: #409eff"
            @click="editCourse(scope.row.id)"
          >
            <el-icon class="el-input__icon"> <edit /> </el-icon>编辑
          </el-button>
          <el-button
            size="small"
            type="text"
            style="color: #f56c6c"
            @click="removeById(scope.row)"
          >
            <el-icon class="el-input__icon"> <delete /> </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>
  </div>
</template>

<script lang="ts">
import {
  getCourse,
  deleteCourse,
  searchCourseReq,
  getUnivById,
} from "#/CourseManagement/course";
import { addLogs } from "#/Home/Home";
import { reactive, toRefs, watch } from "vue-demi";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import TheTable from "@/components/common/TheTable.vue";

export default {
  components: { TheTable },
  setup() {
    const state = reactive({
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        isShow: true,
        placeholder: "请输入课程名称",
      },
      course: [],
      // 统计课程的总数量
      total: 0,
      columns: [
        { name: "课程名称", show: true },
        { name: "课程类型", show: true },
        { name: "教师", show: true },
        { name: "所属机构", show: true },
        { name: "视频数量", show: true },
        { name: "作业数量", show: true },
        { name: "评分", show: true },
        { name: "操作", show: true },
      ],
    });
    const router = useRouter();

    // 改变表单栏显示隐藏状态
    function changeColumn(columns) {
      state.columns = columns;
    }

    // 获取所有课程
    async function getClass() {
      await getCourse(state.queryInfo.pageNum, state.queryInfo.pageSize).then(
        (res) => {
          const result = res.data;
          console.log(result);
          if (result.ret === 0) {
            state.course = result.courses.courses.content;
            state.course.forEach(async (e) => {
              e.score /= 2;
              await getUnivById(e.org_id).then((res) => {
                if (res.status === 200) {
                  console.log(res.data);
                  e.organization = res.data.yniv.schoolName;
                }
              });
            });
            state.total = result.courses.courses.totalElements;
          } else {
            ElMessage.error("服务器请求错误！");
          }
        }
      );
    }
    function goToAdd() {
      router.push("/CourseManagement/addCourse");
    }
    // 搜索课程
    async function search(searchText) {
      if (!searchText) {
        return ElMessage.error("请输入名称");
      }
      state.queryInfo.pageNum = 1;
      await searchCourseReq(
        searchText,
        state.queryInfo.pageNum,
        state.queryInfo.pageSize
      ).then((res) => {
        if (res.status === 200) {
          state.course = res.data.courses.courses.content;
          state.total = res.data.courses.courses.totalElements;
          if (state.course === []) {
            ElMessage.info("搜索结果为空");
          } else {
            ElMessage.success("搜索成功！");
          }
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
    // 清除输入框的内容
    function clearInput() {
      state.queryInfo.pageNum = 1;
      state.queryInfo.pageSize = 5;
      getClass();
    }
    // 打开编辑课程对话框
    function editCourse(id) {
      router.push("/CourseManagement/addCourse?id=" + id);
    }
    // 删除课程
    async function removeById(row) {
      const confirmResult = await ElMessageBox.confirm(
        "此操作将永久删除该课程, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        await deleteCourse(row.id).then(async (res) => {
          if (res.status === 200) {
            ElMessage.success("成功删除课程！");
            await addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "删除了《" + row.name + "》课程",
            });
            getClass();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      }
    }
    // 分页数据改变
    function pageInfoChange(type: string, newValue: number) {
      if (type === "size") state.queryInfo.pageSize = newValue;
      else if (type === "page") state.queryInfo.pageNum = newValue;
      getClass();
    }

    getClass();

    return {
      ...toRefs(state),
      getClass,
      goToAdd,
      search,
      clearInput,
      editCourse,
      removeById,
      pageInfoChange,
      changeColumn,
    };
  },
};
</script>

<style lang="scss" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.page-content {
  width: 100%;
  height: 100%;
  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
}
</style>
